package com.demo.webapp.kcfinder.result;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.demo.webapp.kcfinder.Dispatcher;
import com.demo.webapp.kcfinder.config.NotFoundDispatcherException;
import com.demo.webapp.kcfinder.config.ResultConfig;
import com.demo.webapp.kcfinder.context.ActionContext;
import com.demo.webapp.kcfinder.freemarker.FreemarkerManager;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * Freemarker结果对象映射
 * @author ryuu.kk
 *
 */
public class ActionFreemarkerResult implements Result {

	@Override
	public String render(ActionContext context, ResultConfig config) throws IOException {
		
		Configuration freemarkerConfiguration = null;
		ServletContext servletContext = context.getServletContext();
		HttpServletResponse response = context.getResponse();
		PrintWriter out = response.getWriter();
		String templateName = config.getResult();
		Locale locale = context.getLocale();
		
		//取得线程上下文的调度器
		Dispatcher dispatcher = Dispatcher.getInstance();
		if (dispatcher == null) {
			throw new NotFoundDispatcherException("not found " + Dispatcher.class.getName() + " in current thread.");
		}
		FreemarkerManager manager = dispatcher.getFreemarkerManager();
		try {
			freemarkerConfiguration = manager.getConfiguration(servletContext);
			Template template = freemarkerConfiguration.getTemplate(templateName, locale);
			TemplateModel model = manager.buildTemplateModel(context, ObjectWrapper.BEANS_WRAPPER);
			template.process(model, out);
		} catch (TemplateException e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}
}
